<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/8/12
 * Time: 11:27
 */
class MessageService
{
    private $messageBoxModel;
    private $userService;
    private $autoUidModel;
    private $diaryAttachmentModel;
    private $shopModel;

    const IM_SERVER = 'http://fa.im.fenfenriji.com:8383/api.php';

    function __construct()
    {
        $this->messageBoxModel      =   new MessageBoxModel();
        $this->userService          = new UserService();
        $this->autoUidModel         =   new AutoUidModel();
        $this->diaryAttachmentModel =   new DiaryAttachmentModel();
        $this->shopModel            =   new ShopModel();
    }

    /**
     * 清除私信未读数
     * @param $uid
     * @param $mUid
     * @return bool|int|resource
     */
    public function resetUnReadNum($uid, $mUid)
    {
        return $this->messageBoxModel->resetUnReadNum(array('uid' => $uid, 'mUid' => $mUid));
    }

    public function getMessageListInfo($uid, $mUid)
    {
        return  $this->messageBoxModel->getMessageListInfo(array('uid' => $uid, 'mUid' => $mUid));
    }

    public function sendMessage($uid, $mUid, $data, $count = true, $attachment = FALSE, $voice = FALSE)
    {
        $param = array(
            'uid'      => $uid,
            'mUid'     => $mUid,
            'nickname' => (isset($data['nickname']) && $data['nickname']) ? $data['nickname'] : '粉粉小秘书',
            'mNickname'=> (isset($data['mNickname']) && $data['mNickname']) ? $data['mNickname'] : '粉粉用户',
            'content'  => $data['content'],
        );
        isset($data['msgType']) && $param['msgType'] = $data['msgType'];
        isset($data['msgType']) && isset($data['msgData']) && $param['msgData'] = $data['msgData'];
        $this->sendMsgUserIM($param);
        $count && $this->countTimes([ 'uid'=>$mUid, 'messageTimes'=>1 ]);
        return $this->messageBoxModel->sendMessage($param, $attachment, $voice);
    }

    /**
     * 增加计数
     * @param $info
     */
    public function countTimes($info){
        if (empty($info)) return ;
        $userStatisticsModel = new UserStatisticsModel();
        $userStatisticsModel->userStatistics($info);
        unset(AC::$userStatistics[$info['uid']]['messageTimes']);//防止重复
    }

    /**
     * 发送消息到IM
     * @param $data
     * @return mixed
     */
    public function sendMsgUserIM($data){
        $url = self::IM_SERVER;
        $query = [
            'opid' => $data['uid'],
            'action' => 'sendMessage',
            'uid' => $data['mUid']
        ];
        $url .= '?'. http_build_query($query);
        //组装消息格式，防止客户端闪退
        if (isset($data['msgData']) && !empty($data['msgData'])){
            $data['data'] = json_decode($data['msgData'], true);
            unset($data['msgData']);
        }
        $data['type'] = 1;
        $data['time'] = AC::SERVER_TIME;
        $data['status'] = 0;
        $data['avatar'] = '';
        $data['voiceList'] = [];
        $data['attachment'] = [];
        $data['id'] = 12345678;
        $post_data = [
            'message' => UK::JsonFormat($data)
        ];
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_HEADER, 0 ); // 过滤HTTP头
        curl_setopt($curl, CURLOPT_USERAGENT, "FFRJ-API");
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 3);
        curl_setopt($curl, CURLOPT_TIMEOUT, 3);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);// 显示输出结果
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        $responseText = curl_exec($curl);
        curl_close($curl);
        return $responseText;
    }

    private function saveMessage()
    {

    }

    private function saveAttachments()
    {

    }

    /**
     * 组装数据
     * @param $uid
     * @param $mUid
     * @param $data
     * @return array|bool
     */
    private function buildSendMessageParams($uid, $mUid, $data)
    {
        $user    = $this->userService->getUserInfo($uid);
        $mUser   = $this->userService->getUserInfo($mUid);
        if (empty($user) || empty($mUser))
        {
            return false;
        }

        $result = array(
            'uid'           =>  $uid,
            'mUid'          =>  $mUid,
            'nickname'      =>  $user['nickname'],
            'mNickname'     =>  $mUser['nickname'],
            'content'       =>  $data['content'],
            'voice'         =>  $data['voice'],
            'attachment'    =>  $data['attachment'],
            'data_title'    =>  $data['data_title'],
            'data_image'    =>  $data['data_image'],
            'data_action'   =>  $data['data_action'],
            'data_content'  =>  $data['data_content'],
        );

        return $result;
    }

    private function messageInfoData()
    {

    }

    /**
     * 默认返回的私信数据结构
     * @return array
     */
    private function getDefaultMessageData()
    {
        return array(
            'id'            =>  '',
            'uid'           =>  '',
            'avatar'        =>  '',
            'mUid'          =>  '',
            'mNickname'     =>  '',
            'content'       =>  '',
            'type'          =>  '',
            'msgType'       =>  '',
            'time'          =>  '',
            'data'          =>  (Object) array(),
            'attachment'    =>  array(),
            'voiceList'     =>  array()
        );
    }

    /**
     * 发送私信消息到队列
     * @param $opid
     * @param $uid
     * @param array $data
     * @return mixed
     */
    public function sendMsg2UserQueue($opid, $uid, $data=[]){
        $query = [
            'opid' => $opid,
            'action' => 'sendMessage',
            'uid' => $uid
        ];
        $url = self::IM_SERVER . '?'.http_build_query($query);
        if (isset($data[0]) && is_array($data[0])){
            $data = $data[0];
            $data['type'] = 1;
            $data['content'] = UK::getstr($data['content'], 512, '..', 1);
        }else{
            $data = [];
        }
        $data = [
            'do' => 'sendMessage',
            'url' => $url,
            'message' => $data
        ];
        $data = UK::JsonFormat($data);
        RedisPool::addChatMsg2IMCreateJob('sendMessage', $data);
//        return UK::getHttpResponsePOST($url, $data);
    }

    public function rebuildData($data) {
        if(empty($data)) return $data;
        $tmp = [];
        $tmpUserInfo         =    $this->autoUidModel->getUserInfo($data['mUid']);
        $data['avatar']     =    $tmpUserInfo['avatar'];
        $data['mNickname']  =    $this->autoUidModel->getRemarkName($tmpUserInfo);
        // 获取附件
        $tmp['uid']         =   $data['uid'];
        $tmp['last_attachment']          =   UK::getBodyidByItemid('MC/'. $data['uid'], $data['id']);
        if ( $data['type'] == 1){
            $tmp['uid']         =   $data['mUid'];
            $tmp['last_attachment']      =   UK::getBodyidByItemid('MC/'. $data['mUid'], $data['mid']);
        }
        $data['attachmentList']    =    array();
        $data['voiceList']         =    array();
        if ($tmp['last_attachment']){
            $attachment         =   $this->diaryAttachmentModel->getMessageAttachment($tmp);
            if ($attachment['attachment'] || $attachment['voiceList']){
                $data['attachment']    =    $attachment['attachment'];
                $data['voiceList']     =    $attachment['voiceList'];
            }
        }
        $result  = $this->structureMessageInfoData($data);
        return $result;
    }

    private function structureMessageInfoData($param){
        $data = array(
            'id'           =>    '0',
            'uid'          =>    '0',
            'mUid'         =>    '0',
            'mNickname'    =>    '',
            'avatar'       =>    '',
            'type'         =>    '',
            'msgType'      =>    '',
            'content'      =>    '',
            'time'         =>    AC::SERVER_TIME,
            'status'       =>    '0',
            'data'         =>    (Object) array(),
            'attachment'   =>    array(),
            'voiceList'    =>    array(),
        );

        isset($param['id'])           &&    $data['id']           =    strval($param['id']);
        isset($param['uid'])          &&    $data['uid']          =    strval($param['uid']);
        isset($param['mUid'])         &&    $data['mUid']         =    strval($param['mUid']);
        isset($param['mNickname'])    &&    $data['mNickname']    =    strval($param['mNickname']);
        isset($param['avatar'])       &&    $data['avatar']       =    strval($param['avatar']);
        isset($param['type'])         &&    $data['type']         =    strval($param['type']);
        isset($param['msgType'])      &&    $data['msgType']      =    strval($param['msgType']);
        isset($param['content'])      &&    $data['content']      =    strval($param['content']);
        isset($param['time'])         &&    $data['time']         =    strval($param['time']);
        isset($param['status'])       &&    $data['status']       =    strval($param['status']);
        isset($param['attachment'])   &&    $data['attachment']   =    $param['attachment'];
        isset($param['voiceList'])    &&    $data['voiceList']    =    $param['voiceList'];
        // 匹配查找表情
        $emotionData = Emotion::matchEmotionDetail($data['content']);
        if ($emotionData && $emotionData['id'] > 0){
            $emotionInfo = $this->shopModel->getGoodsDetailByGoodsType($emotionData['id'], 1, 'Shop-Emotion');
            if ($emotionInfo){
                $data['msgType'] = $param['msgType'] = 'emotion';
                $msgData = array(
                    'eid'    =>    $emotionInfo['id'],
                    'etitle' =>    $emotionInfo['name'],
                    'eicon'  =>    $emotionInfo['cover_s'],
                    'image'  =>    $emotionData['image']
                );
                $param['msgData'] = json_encode($msgData);
            }
        }

        // 私信返回附加媒体信息
        $data['data'] = $this->shopModel->restructMsgData($param['msgType'], $param['msgData']);

        // 附件支持,升级提示
        $tipsAttachment = $data['attachment'];
        if (!empty($data['voiceList'])){
            $tipsAttachment = $data['voiceList'];
        }
        $data['content'] = UK::tipsUpgrade($tipsAttachment, $data['content'], 'attachment');
        return $data;
    }

}